(function(){
  const excelPathInput = document.getElementById('excelPath');
  const fileInput = document.getElementById('file-input');
  const logEl = document.getElementById('log');
  const envStatusEl = document.getElementById('envStatus');
  const statusIndicatorEl = document.getElementById('statusIndicator');
  const btnOpen = document.getElementById('btn-open');
  const btnRun = document.getElementById('btn-run');
  const btnStop = document.getElementById('btn-stop');
  const btnInstall = document.getElementById('btn-install');
  const passwordToggle = document.getElementById('passwordToggle');
  const passwordInput = document.getElementById('password');
  const usernameInput = document.getElementById('username');
  const pluginName = 'BO-Input';

  // 本地存储键名
  const STORAGE_KEYS = {
    username: 'bo-input-username',
    password: 'bo-input-password'
  };

  // 密码显示状态
  let isPasswordVisible = false;

  function appendLog(message, type = 'info') {
    const ts = new Date().toLocaleString();
    logEl.textContent += `[${ts}] ${type.toUpperCase()}: ${message}\n`;
    logEl.scrollTop = logEl.scrollHeight;
  }

  function setButtonsRunningState(running) {
    btnRun.disabled = running || !excelPathInput.value;
    btnStop.disabled = !running;
  }

  // 环境检查
  window.pyAPI.checkPythonEnvironmentForPlugin(pluginName).then((status) => {
    envStatusEl.textContent = `Python 环境：${status.installed ? '已安装' : '未安装'}` + (status.version ? `，版本 ${status.version}` : '');
    
    // 如果Python环境已安装且已选择文件，启用运行按钮
    if (status.installed && excelPathInput.value) {
      setButtonState(btnRun, true, '开始执行');
    }
  }).catch(err => {
    appendLog(`检查Python环境失败：${err.message}`, 'error');
  });

  // 更新状态显示函数
  function updateStatus(message, type = 'info') {
    envStatusEl.textContent = message;
    
    // 更新状态指示器
    if (statusIndicatorEl) {
      statusIndicatorEl.className = 'status-indicator';
      if (type === 'success') {
        statusIndicatorEl.classList.add('success');
      } else if (type === 'error') {
        statusIndicatorEl.classList.add('error');
      }
    }
  }

  // 本地存储功能
  function saveCredentials() {
    try {
      localStorage.setItem(STORAGE_KEYS.username, usernameInput.value);
      localStorage.setItem(STORAGE_KEYS.password, passwordInput.value);
    } catch (error) {
      console.error('保存凭据失败:', error);
    }
  }

  function loadCredentials() {
    try {
      const savedUsername = localStorage.getItem(STORAGE_KEYS.username);
      const savedPassword = localStorage.getItem(STORAGE_KEYS.password);
      
      if (savedUsername) {
        usernameInput.value = savedUsername;
      }
      if (savedPassword) {
        passwordInput.value = savedPassword;
      }
    } catch (error) {
      console.error('加载凭据失败:', error);
    }
  }

  // 密码显示/隐藏切换功能
  function togglePasswordVisibility() {
    isPasswordVisible = !isPasswordVisible;
    passwordInput.type = isPasswordVisible ? 'text' : 'password';
    
    // 更新按钮图标
    const svg = passwordToggle.querySelector('svg');
    if (isPasswordVisible) {
      // 显示密码时使用"隐藏"图标
      svg.innerHTML = `
        <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94L17.94 17.94z"></path>
        <path d="M1 1l22 22"></path>
        <path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19l-6.65-6.65a3 3 0 0 0-4.24-4.24L9.9 4.24z"></path>
      `;
    } else {
      // 隐藏密码时使用"显示"图标
      svg.innerHTML = `
        <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
        <circle cx="12" cy="12" r="3"></circle>
      `;
    }
  }

  // 设置按钮状态
  function setButtonState(button, enabled, text) {
    button.disabled = !enabled;
    if (text) {
      // 保留图标，只更新文本部分
      const icon = button.textContent.split(' ')[0];
      button.textContent = `${icon} ${text}`;
    }
  }

  // 安装依赖
  btnInstall.addEventListener('click', async () => {
    try {
      appendLog('开始安装依赖...');
      const res = await window.pyAPI.runpyfile({
        pluginName,
        fileName: 'install_dependencies.py',
        args: []
      });
      appendLog(res.success ? '依赖安装完成' : `依赖安装失败：${res.error || '未知错误'}`);
    } catch (err) {
      appendLog(`安装依赖出错：${err.message}`, 'error');
    }
  });



  window.pyAPI.onPythonProcessEnded((end) => {
    setButtonsRunningState(false);
    appendLog(end.success ? '任务完成' : `任务失败，退出码 ${end.code}`);
  });
  window.pyAPI.onPythonProcessError((err) => {
    setButtonsRunningState(false);
    appendLog(`进程错误：${err.error}`, 'error');
  });

  // 环境检查
  async function checkPythonEnv() {
    try {
      updateStatus('正在检查Python环境...', 'info');
      
      const result = await window.electronAPI.runCommand('python --version');
      if (result.success) {
        updateStatus(`Python环境正常: ${result.output.trim()}`, 'success');
        setButtonState(btnRun, excelPathInput.value.trim() !== '', '开始执行');
      } else {
        updateStatus('Python环境未找到，请安装Python', 'error');
        setButtonState(btnRun, false, '开始执行');
      }
    } catch (error) {
      updateStatus('检查Python环境时出错', 'error');
      setButtonState(btnRun, false, '开始执行');
    }
  }

  // 打开Excel文件 - 使用fileAPI方式
  if (btnOpen) {
    btnOpen.addEventListener('click', selectExcelFile);
  } else {
    console.error('btnOpen 元素未找到');
    appendLog('错误：打开按钮元素未找到', 'error');
  }

  // 监听Python输出（监控数据透传到主进程）
  window.pyAPI.onPythonLogOutput((log) => {
    try {
      // 确保正确处理UTF-8编码的文本
      let text = '';
      if (log.data) {
        if (typeof log.data === 'string') {
          text = log.data;
        } else if (log.data instanceof ArrayBuffer) {
          // 如果是二进制数据，使用UTF-8解码
          const decoder = new TextDecoder('utf-8');
          text = decoder.decode(log.data);
        } else {
          text = String(log.data);
        }
      }
      
      if (log.type !== 'stderr' && text.startsWith('MONITORING_DATA:')) {
        const jsonStr = text.replace('MONITORING_DATA:', '');
        const payload = JSON.parse(jsonStr);
        if (window.electronAPI && typeof window.electronAPI.sendMonitoringData === 'function') {
          window.electronAPI.sendMonitoringData(payload).catch(err => {
            appendLog(`监控数据发送失败：${err.message}`, 'error');
          });
        }
      } else {
        appendLog(text, log.type === 'stderr' ? 'error' : 'info');
      }
    } catch (e) {
      appendLog(`解析Python输出失败：${e.message}`, 'error');
    }
  });

  window.pyAPI.onPythonProcessEnded((end) => {
    setButtonsRunningState(false);
    appendLog(end.success ? '任务完成' : `任务失败，退出码 ${end.code}`);
  });

  window.pyAPI.onPythonProcessError((err) => {
    setButtonsRunningState(false);
    appendLog(`进程错误：${err.error}`, 'error');
  });

  // 执行Python脚本
  btnRun.addEventListener('click', async () => {
    const xlsPath = excelPathInput.value;
    if (!xlsPath) {
      appendLog('请先选择Excel文件', 'warn');
      return;
    }

    // 获取配置参数
    const boAddress = document.getElementById('boAddress').value;
    const defaultTimeout = parseInt(document.getElementById('defaultTimeout').value);
    const timeout = parseInt(document.getElementById('timeout').value);
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    // 验证必填字段
    if (!boAddress || !username || !password) {
      appendLog('请填写完整的配置信息（BO地址、用户名、密码）', 'warn');
      return;
    }

    // 保存凭据到本地存储
    saveCredentials();

    // 获取浏览器模式设置
    const browserMode = window.getBrowserMode ? window.getBrowserMode() : { headless: true };

    // 构建配置JSON
    const configData = {
      boAddress: boAddress,
      defaultTimeout: defaultTimeout,
      timeout: timeout,
      username: username,
      password: password,
      headless: browserMode.headless
    };

    try {
      setButtonsRunningState(true);
      appendLog('开始执行脚本...');
      const res = await window.pyAPI.runpyfile({
        pluginName,
        fileName: 'BO_Input.py',
        args: [xlsPath, JSON.stringify(configData)]
      });
      if (!res.success) {
        appendLog(`执行失败：${res.error || '未知错误'}`, 'error');
      }
    } catch (err) {
      setButtonsRunningState(false);
      appendLog(`运行出错：${err.message}`, 'error');
    }
  });
  // 停止执行
  btnStop.addEventListener('click', async () => {
    try {
      await window.electronAPI.stopPythonScript();
      appendLog('已停止执行');
      updateStatus('执行已停止', 'info');
      setButtonState(btnRun, true, '开始执行');
      setButtonState(btnStop, false, '停止');
    } catch (error) {
      appendLog('停止执行时出错: ' + error.message, 'error');
    }
  });

  /**
   * 选择Excel文件
   */
  async function selectExcelFile() {
    console.log('selectExcelFile 函数被调用');
    try {
      if (window.fileAPI && window.fileAPI.showOpenDialog) {
        const result = await window.fileAPI.showOpenDialog({
          title: '选择Excel文件',
          filters: [
            { name: 'Excel文档', extensions: ['xlsx', 'xls'] },
            { name: '所有文件', extensions: ['*'] }
          ],
          properties: ['openFile']
        });
        
        console.log('showOpenDialog 返回结果:', result);
        
        if (result.success && result.data && !result.data.canceled && result.data.filePaths && result.data.filePaths.length > 0) {
          const filePath = result.data.filePaths[0];
          excelPathInput.value = filePath;
          appendLog(`已选择Excel文件: ${filePath}`);
          
          // 检查是否可以启用运行按钮
          if (envStatusEl.textContent.includes('已安装')) {
            setButtonState(btnRun, true, '开始执行');
          } else {
            appendLog('请先确保Python环境已安装', 'warning');
          }
        } else if (result.success && result.data && result.data.canceled) {
          appendLog('用户取消了Excel文件选择', 'info');
        } else {
          appendLog(`选择Excel文件失败: ${result.error || '未知错误'}`, 'error');
        }
      } else {
        console.log('fileAPI 不可用:', { fileAPI: window.fileAPI, showOpenDialog: window.fileAPI?.showOpenDialog });
        appendLog('文件选择API不可用', 'error');
      }
    } catch (error) {
      appendLog(`选择Excel文件失败: ${error.message}`, 'error');
      console.error('选择Excel文件失败:', error);
    }
  }

  // 初始化事件监听器和加载保存的凭据
  function initialize() {
    // 加载保存的凭据
    loadCredentials();
    
    // 密码切换按钮事件监听器
    if (passwordToggle) {
      passwordToggle.addEventListener('click', togglePasswordVisibility);
    }
    
    // 输入框变化时自动保存
    if (usernameInput) {
      usernameInput.addEventListener('blur', saveCredentials);
    }
    if (passwordInput) {
      passwordInput.addEventListener('blur', saveCredentials);
    }
  }

  // 页面加载完成后初始化
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initialize);
  } else {
    initialize();
  }

})();